<template>
  <div class="px-6 py-8 w-full md:w-[90%] lg:w-[80%] m-auto overflow-y-auto h-[calc(100vh-3.5rem)] relative hide-scrollbar">
    <!-- 单元列表 -->
    <transition 
      name="fade" 
      mode="out-in"
      enter-active-class="transition-all duration-300 ease-out" 
      leave-active-class="transition-none"
      enter-from-class="opacity-0" 
      enter-to-class="opacity-100"
      leave-from-class="opacity-100" 
      leave-to-class="opacity-0"
    >
      <UnitsList 
        v-if="!selectedUnitId" 
        :units="units" 
        @select-unit="selectUnit" 
      />
      
      <UnitDetail
        v-else
        :unit="currentUnit"
        :lessons="filteredLessons"
        :is-new-lesson-disabled="isNewLessonDisabled"
        :container-height="containerHeight"
        @back="selectedUnitId = null"
        @create-course="createNewCourse"
        @select-lesson="handleLessonClick"
      />
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { 
  getAllUnits,
  getUnitCourses,
  createUnitProgress,
} from '@/api/unit';
import { useModalStore } from '@/stores/modal';
import { useProgress } from '@/composables/useProgress';
import { useSettingsStore } from '@/stores/settings';

// 导入子组件
import UnitsList from './components/UnitsList.vue';
import UnitDetail from './components/UnitDetail.vue';

// ==================== 路由相关 ====================
const router = useRouter();
const route = useRoute();

// ==================== 读取存储 ====================
const modalStore = useModalStore();
const progressManager = useProgress();
const settingsStore = useSettingsStore();

// ==================== 常量定义 ====================
const CARD_CONFIG = {
  size: 160,
  verticalGap: 50,
  minProgress: 100
};

// ==================== 状态管理 ====================
const selectedUnitId = ref(null);
const units = ref([]);
const allLessons = ref([]);

// ==================== 计算属性 ====================
const currentUnit = computed(() => units.value.find(unit => unit.id === selectedUnitId.value));
const filteredLessons = computed(() => allLessons.value);
const isNewLessonDisabled = computed(() => {
  // 如果没有课程，允许创建第一个课程
  if (filteredLessons.value.length === 0) {
    return false;
  }
  
  // 检查最后一个课程是否完成（进度为100%）
  const lastLesson = filteredLessons.value[filteredLessons.value.length - 1];
  return lastLesson && lastLesson.progress < 100;
});
const containerHeight = computed(() => {
  // 计算容器的总高度，加上额外的空间用于hover效果
  const totalCards = filteredLessons.value.length + 1; // +1 是为了新建按钮
  return `${totalCards * (CARD_CONFIG.size + CARD_CONFIG.verticalGap) + 24}px`;
});

// ==================== 数据加载函数 ====================
const fetchVocabularyProgress = async () => {
  console.log('开始获取单元数据...');
  try {
    const response = await getAllUnits(settingsStore.bookType);
    console.log('获取单元响应:', response);
    if (response.code === 0) {
      units.value = formatUnitsData(response.data);
      console.log('单元数据格式化完成:', units.value);
    } else {
      console.error('获取单元数据失败:', response);
    }
  } catch (error) {
    console.error('获取单元信息出错:', error);
  }
};

const formatUnitsData = (data) => {
  return data.units.map(unit => ({
    id: unit.id.toString(),
    title: unit.name,
    locked: unit.level > 2,
    progress: progressManager.calculateProgress(unit.progresses?.words_learned, unit.progresses?.words_total),
    words: `${unit.progresses?.words_learned || 0}/${unit.word_count}`,
    description: unit.description,
    level: unit.level,
    order: unit.order
  }));
};

const calculateProgress = (learned = 0, total = 0) => {
  if (!total) return 0;
  // 确保进度不超过100%
  return Math.min(100, Math.round((learned / total) * 100));
};

// ==================== 本地存储功能 ====================
const STORAGE_KEY = 'lastOpenedUnit';

const saveLastOpenedUnit = (unitId) => {
  try {
    localStorage.setItem(STORAGE_KEY, unitId.toString());
    // 同时更新到 modalStore
    modalStore.setLastUnit(unitId.toString());
  } catch (error) {
    console.error('保存上次打开的单元失败:', error);
  }
};

const getLastOpenedUnit = () => {
  try {
    // 优先从 modalStore 获取
    if (modalStore.lastUnitId) {
      return modalStore.lastUnitId;
    }
    return localStorage.getItem(STORAGE_KEY);
  } catch (error) {
    console.error('获取上次打开的单元失败:', error);
    return null;
  }
};

// ==================== 交互处理函数 ====================
const selectUnit = async (unitId) => {
  console.log('选择单元:', unitId);
  const unit = units.value.find(u => u.id === unitId);
  if (!unit || unit.locked) {
    console.warn('单元不存在或已锁定:', unitId);
    return;
  }
  
  try {
    console.log('获取单元课程:', unitId);
    const response = await getUnitCourses(unitId);
    if (response.code === 0) {
      allLessons.value = formatCoursesData(response.data);
      updateSelectedUnit(unitId);
      console.log('成功加载单元课程:', unitId);
      
      // 课程加载完成后，滚动到上次学习的课程
      nextTick(() => {
        scrollToLastCourse();
      });
    }
  } catch (error) {
    console.error('选择单元失败:', error);
    showToast('选择单元失败，请稍后重试', 'error');
  }
};

const formatCoursesData = (courses) => {
  return courses.map((course, index) => ({
    id: course.course_id,
    name: `第${index + 1}课`,
    unitId: course.unit_id,
    locked: false,
    progress: progressManager.calculateProgress(course.words_learned, course.words_total),
    words_learned: course.words_learned,
    words_total: course.words_total,
    is_completed: course.is_completed,
    last_studied_at: course.last_studied_at
  }));
};

const updateSelectedUnit = (unitId) => {
  console.log('更新选中的单元:', unitId);
  selectedUnitId.value = unitId;
  router.push({ 
    path: '/home/speaking', 
    query: { unit: unitId } 
  });
  console.log('更新路由参数:', { unit: unitId });
  saveLastOpenedUnit(unitId);
};

const createNewCourse = async () => {
  try {
    const response = await createUnitProgress(selectedUnitId.value.toString());
    if (response.code === 0 && response.data) {
      addNewCourse(response.data);
      showToast('成功创建新课程', 'info');
    }
  } catch (error) {
    console.error('创建新课程失败:', error);
    showToast('请先完成上一关卡的文章', 'error');
  }
};

const addNewCourse = (courseData) => {
  const newCourse = {
    id: courseData.course_id,
    name: `第${allLessons.value.length + 1}课`,
    unitId: courseData.unit_id,
    locked: false,
    progress: 0,
    words_learned: 0,
    words_total: courseData.words_total || 0,
    is_completed: false,
    last_studied_at: null
  };
  allLessons.value.push(newCourse);
};

const handleLessonClick = async (lesson) => {
  if (lesson.locked) return;
  try {
    // 保存当前点击的课程ID到 modalStore
    modalStore.setLastCourse(lesson.id);
    router.push(`/speaking/vocabulary/${lesson.id}`);
  } catch (error) {
    console.error('处理课程点击失败:', error);
    showToast('操作失败，请稍后重试', 'error');
  }
};

// 添加滚动到上次学习课程的函数
const scrollToLastCourse = () => {
  const lastCourseId = modalStore.lastCourseId;
  if (!lastCourseId || filteredLessons.value.length === 0) return;
  
  // 查找上次学习的课程索引
  const courseIndex = filteredLessons.value.findIndex(lesson => lesson.id === lastCourseId);
  if (courseIndex === -1) return;
  
  // 计算滚动位置
  const scrollPosition = courseIndex * (CARD_CONFIG.size + CARD_CONFIG.verticalGap);
  
  // 执行滚动
  const scrollContainer = document.querySelector('.overflow-y-auto');
  if (scrollContainer) {
    console.log('滚动到上次学习的课程:', lastCourseId, '位置:', scrollPosition);
    scrollContainer.scrollTo({
      top: scrollPosition,
      behavior: 'smooth'
    });
  }
};

// ==================== 通知函数 ====================
const showToast = (message, type = 'info') => {
  const toast = createToastElement(message, type);
  document.body.appendChild(toast);
  setTimeout(() => toast.remove(), 2500);
  return toast;
};

const createToastElement = (message, type) => {
  const toast = document.createElement('div');
  toast.className = `toast toast-${type}`;
  toast.textContent = message;
  
  Object.assign(toast.style, {
    position: 'fixed',
    top: '20px',
    left: '50%',
    transform: 'translateX(-50%)',
    padding: '10px 20px',
    borderRadius: '4px',
    backgroundColor: type === 'error' ? '#f44336' : '#333',
    color: 'white',
    zIndex: '9999',
    boxShadow: '0 2px 8px rgba(0,0,0,0.2)'
  });
  
  return toast;
};

const closeToast = (toast) => {
  toast?.parentNode?.removeChild(toast);
};

// ==================== 生命周期钩子 ====================
onMounted(async () => {
  console.log('组件挂载，开始初始化...');
  
  // 确保settingsStore已初始化
  if (!settingsStore.initialized) {
    await settingsStore.fetchSettings();
  }
  
  await fetchVocabularyProgress();
  console.log('单元数据加载完成，准备初始化路由');
  initializeFromRoute();
});

const initializeFromRoute = () => {
  // 优先使用URL中的unit参数
  const { unit } = route.query;
  console.log('从URL获取单元参数:', unit, typeof unit);
  
  if (unit) {
    // 确保单元ID为字符串类型
    const unitId = unit;
    console.log('从URL初始化单元:', unitId);
    selectUnitIfValid(unitId);
    return;
  }
  
  // 如果URL中没有unit参数，尝试从 modalStore 或本地存储获取
  const lastOpenedUnit = getLastOpenedUnit();
  console.log('从存储获取上次打开的单元:', lastOpenedUnit);
  
  if (lastOpenedUnit) {
    // 确保单元ID为字符串类型
    const unitId = lastOpenedUnit;
    console.log('从存储初始化单元:', unitId);
    selectUnitIfValid(unitId);
  }
};

const selectUnitIfValid = async (unitId) => {
  // 等待units加载完成
  if (units.value.length === 0) {
    console.log('单元数据尚未加载完成，等待100ms后重试...');
    setTimeout(() => selectUnitIfValid(unitId), 100);
    return;
  }
  
  console.log('尝试打开单元ID:', unitId, '当前可用单元:', units.value);
  // 使用字符串比较，确保ID类型一致
  const validUnit = units.value.find(u => {
    console.log('比较单元:', u.id, typeof u.id, '目标ID:', unitId.toString(), typeof unitId.toString());
    return u.id === unitId.toString() && !u.locked;
  });
  
  if (validUnit) {
    console.log('找到有效单元:', validUnit);
    // 检查当前选中的单元ID是否已经是目标单元ID
    if (selectedUnitId.value === unitId.toString()) {
      console.log('单元已经被选中，无需重新加载:', unitId.toString());
      return;
    }
    
    try {
      // 直接获取课程数据
      const response = await getUnitCourses(unitId.toString());
      if (response.code === 0) {
        allLessons.value = formatCoursesData(response.data);
        // 设置选中的单元ID
        selectedUnitId.value = unitId.toString();
        // 保存到本地存储
        saveLastOpenedUnit(unitId.toString());
        console.log('成功加载单元课程，单元ID:', unitId.toString());
        
        // 课程加载完成后，滚动到上次学习的课程
        nextTick(() => {
          scrollToLastCourse();
        });
      }
    } catch (error) {
      console.error('加载单元课程失败:', error);
    }
  } else {
    console.warn('未找到有效单元或单元已锁定，ID:', unitId.toString());
  }
};

// ==================== 路由监听 ====================
watch(() => route.query.unit, (newUnit, oldUnit) => {
  console.log('路由参数变化 unit:', newUnit, typeof newUnit, 'oldUnit:', oldUnit);
  if (!newUnit) {
    selectedUnitId.value = null;
    return;
  }
  
  // 如果新旧值相同，不重复加载
  if (newUnit === oldUnit) {
    console.log('单元ID未变化，跳过重新加载');
    return;
  }
  
  // 直接使用字符串类型的单元ID
  const unitId = newUnit;
  console.log('监听到路由变化，准备选择单元:', unitId);
  selectUnitIfValid(unitId);
});

// 添加对bookType变化的监听
watch(() => settingsStore.bookType, async (newBookType, oldBookType) => {
  if (newBookType !== oldBookType) {
    console.log('词书类型变化，重新加载单元数据:', newBookType);
    selectedUnitId.value = null; // 清除当前选中的单元
    await fetchVocabularyProgress(); // 重新加载单元数据
  }
});
</script>

<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');

.font-inter {
  font-family: 'Inter', sans-serif;
}

.hide-scrollbar {
  -ms-overflow-style: none;
  scrollbar-width: none;
  &::-webkit-scrollbar {
    display: none;
  }
}

.fade-enter-active {
  transition: opacity 0.3s ease;
}

.fade-leave-active {
  transition: none;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 